package com.example.hjt_java_web_homework3.dao;

import com.example.hjt_java_web_homework3.model.EnvironmentData;
import com.example.hjt_java_web_homework3.util.DatabaseUtil;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Repository;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Li Chun Hei
 * @date 31/10/2025
 * @description
 */

@Repository
public class EnvironmentDataDao {
    private static final Logger logger = LogManager.getLogger(EnvironmentDataDao.class);

    public boolean save(EnvironmentData data) {
        String sql = "INSERT INTO environment_data (temperature, humidity, energy_consumption, location) VALUES (?, ?, ?, ?)";

        try (Connection conn = DatabaseUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) {

            pstmt.setBigDecimal(1, data.getTemperature());
            pstmt.setBigDecimal(2, data.getHumidity());
            pstmt.setBigDecimal(3, data.getEnergyConsumption());
            pstmt.setString(4, data.getLocation());

            int affectedRows = pstmt.executeUpdate();
            if (affectedRows > 0) {
                try (ResultSet generatedKeys = pstmt.getGeneratedKeys()) {
                    if (generatedKeys.next()) {
                        data.setId(generatedKeys.getLong(1));
                    }
                }
                logger.info("Saved environment data for location: {}", data.getLocation());
                return true;
            }

        } catch (SQLException e) {
            logger.error("Failed to save environment data", e);
        }
        return false;
    }

    public List<EnvironmentData> findAll() {
        List<EnvironmentData> dataList = new ArrayList<>();
        String sql = "SELECT * FROM environment_data ORDER BY recorded_at DESC";

        try (Connection conn = DatabaseUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql);
             ResultSet rs = pstmt.executeQuery()) {

            while (rs.next()) {
                dataList.add(mapResultSetToEnvironmentData(rs));
            }
            logger.info("Found {} environment data records", dataList.size());

        } catch (SQLException e) {
            logger.error("Failed to find all environment data", e);
        }
        return dataList;
    }

    public List<EnvironmentData> findByLocation(String location) {
        List<EnvironmentData> dataList = new ArrayList<>();
        String sql = "SELECT * FROM environment_data WHERE location = ? ORDER BY recorded_at DESC";

        try (Connection conn = DatabaseUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {

            pstmt.setString(1, location);
            try (ResultSet rs = pstmt.executeQuery()) {
                while (rs.next()) {
                    dataList.add(mapResultSetToEnvironmentData(rs));
                }
            }
            logger.info("Found {} environment data records for location: {}", dataList.size(), location);

        } catch (SQLException e) {
            logger.error("Failed to find environment data by location: {}", location, e);
        }
        return dataList;
    }

    private EnvironmentData mapResultSetToEnvironmentData(ResultSet rs) throws SQLException {
        EnvironmentData data = new EnvironmentData();
        data.setId(rs.getLong("id"));
        data.setTemperature(rs.getBigDecimal("temperature"));
        data.setHumidity(rs.getBigDecimal("humidity"));
        data.setEnergyConsumption(rs.getBigDecimal("energy_consumption"));
        data.setLocation(rs.getString("location"));
        data.setRecordedAt(rs.getTimestamp("recorded_at"));
        return data;
    }
}
